const signService = require('../service/sign');
const sha1 = require('sha1');
const axios = require('axios');
router.post('/shareText', async (req, res) => {
    const {
        unionId,
        openId
    } = req.body;
    //判断是否关注公众号,添加分享记录
    const dateStr = moment().format('YYYYMMDDHHmmss');

    const {
        addSharTextRecordResult
    } = await signService.addSharTextRecord(unionId, openId, dateStr);
    res.json({
        respCode: "0000",
        respMsg: "操作成功!",
        respData: addSharTextRecordResult,
    })
});

router.post('/isFocusWxPub', async (req, res) => {
    const {
        unionId,
        openId
    } = req.body;
    //判断是否关注公众号
    const isFocusWxPub = await signService.isFocusWxPub(unionId, openId);
    if (!isFocusWxPub || isFocusWxPub.status == 0) {
        res.json({
            respCode: "1002",
            respMsg: "请关注公众号!",
            respData: false,
        })
        return;
    }
    res.json({
        respCode: "0000",
        respMsg: "操作成功",
        respData: true,
    })
});

//微信游戏红包提现
router.post('/getOpenId', async (req, res) => {
    const code = req.body.code || "";
    //微信公众号的配置
    const {
        appid: appId
    } = config.zainagzh;
    const appSercret = await cache.hget(`eggsy_cao:${appId}`, 'secret');
    const getWXtokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSercret}&code=${code}&grant_type=authorization_code`;
    const wxResult = await axios({
        method: "GET",
        url: getWXtokenUrl
    });
    const {
        access_token,
        openid,
        unionid
    } = wxResult.data;
    console.log('获取微信用户信息,', wxResult.data);
    const {
        data: userInfo
    } = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`)
    res.json({
        respCode: "0000",
        respMsg: "操作成功",
        respData: {
            userInfo,
            baseUserInfo: wxResult.data
        },
    })
})

router.post('/ticketSign', async (req, res) => {
    const shareTextUrl = req.body.shareTextUrl || 'https://www.baidu.com/dist/forward/index.html';
    const {
        appid: appId
    } = config.zainagzh;
    const accessToken = await cache.hget(`eggsy_cao:${appId}`, 'access_token');
    let ticket = await cache.get('wx:jsticket');
    if (!ticket) {
        const getTicketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`;
        const {
            data: getTicketResult
        } = await axios({
            method: "GET",
            url: getTicketUrl,
        })
        console.log('获取微信ticket返回信息', getTicketResult);
        if (getTicketResult.errmsg != 'ok') {
            res.json({
                respCode: "1002",
                respMsg: "获取微信签名ticket信息出错",
                respData: getTicketResult,
            })
            return;
        }
        ticket = getTicketResult.ticket;
        await cache.set('wx:jsticket', ticket, 'EX', 60 * 60);
    }

    //签名字符串start
    const ret = {
        jsapi_ticket: ticket,
        nonceStr: Math.random().toString(36).substr(2, 15),
        timestamp: parseInt(new Date().getTime() / 1000).toString(),
        url: shareTextUrl
    }
    var keys = Object.keys(ret);
    keys = keys.sort()
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key.toLowerCase()] = ret[key];
    });
    var signStr = '';
    for (var k in newArgs) {
        signStr += '&' + k + '=' + newArgs[k];
    }
    signStr = signStr.substr(1);
    console.log('signStr', signStr)

    //签名字符串end
    const shaObjs = sha1(signStr);
    ret.sign = shaObjs;
    res.json({
        respCode: "0000",
        respMsg: "获取微信签名ticket信息ok",
        respData: ret,
    })

})

module.exports = router;